package com.song.sample.config.pagination;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;

import java.util.ArrayList;
import java.util.List;

/**
 * @desc: 分页参数(同时支持排序，如果不需要排序可以不用传入orderBy参数)
 * @author: WUSONG
 * @date: 2018/7/5 0005 上午 9:56
 */
public class PageRequestParam {
    /**页码，默认第一页*/
    private int pageNum = 1;
    /**每页显示条数，默认显示20条*/
    private int pageSize = 20;
    /**排序字段*/
    private List<OrderBy> orderBy;

    public PageRequestParam() {
    }

    public PageRequestParam(int pageNum, int pageSize) {
        this.pageNum = pageNum;
        this.pageSize = pageSize;
    }

    public PageRequestParam(int pageNum, int pageSize, List<OrderBy> orderBy) {
        this.pageNum = pageNum;
        this.pageSize = pageSize;
        this.orderBy = orderBy;
    }

    public PageRequest build(){
        if (orderBy == null || orderBy.size() == 0)//无序排序的
            return new PageRequest(this.getPageNum()-1,this.pageSize);
        else{
            List<Sort.Order> orderList = new ArrayList<>();
            for (OrderBy by : orderBy) {
                Sort.Order order = new Sort.Order(Sort.Direction.fromString(by.getDirection()),by.getProperty());
                orderList.add(order);
            }
            return new PageRequest(this.getPageNum()-1,
                    this.pageSize, new Sort(orderList));
        }
    }

    private static class OrderBy{
        private String direction;
        private String property;

        public OrderBy() {
        }

        public String getDirection() {
            return direction;
        }

        public void setDirection(String direction) {
            this.direction = direction;
        }

        public String getProperty() {
            return property;
        }

        public void setProperty(String property) {
            this.property = property;
        }
    }




    public int getPageNum() {
        return pageNum;
    }

    public void setPageNum(int pageNum) {
        this.pageNum = pageNum;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }
}
